﻿using System.Windows;

using Microsoft.Extensions.DependencyInjection;

using TimeSpan.Views.Windows;

namespace TimeSpan.Services;

public class DialogService(IServiceProvider service) : IDialogService {

    public void DisplayDialog<TObject, TWindow>(TObject obj)
        where TObject : class
        where TWindow : Window, IEditor<TObject>, new() {

        var dialog = new TWindow {
            ObjectToEdit = obj,
            Owner = service.GetRequiredService<MainWindow>(),
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
        };

        dialog.DataContext = dialog;
        dialog.ShowDialog();

    }

    public TObject? EditWithDialog<TObject, TWindow>(TObject obj)
        where TObject : class
        where TWindow : Window, IEditor<TObject>, new() {

        var dialog = new TWindow {
            ObjectToEdit = obj.JsonClone(),
            Owner = service.GetRequiredService<MainWindow>(),
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
        };

        dialog.DataContext = dialog;

        return dialog.ShowDialog().GetValueOrDefault(false) ? dialog.ObjectToEdit : null;
    }

    public TObject? EditWithDialog<TObject, TWindow>()
        where TObject : class, new()
        where TWindow : Window, IEditor<TObject>, new() {

        return EditWithDialog<TObject, TWindow>(new());
    }

    public TResult GetDialogResult<TObject, TWindow, TResult>(TObject obj)
        where TObject : class
        where TWindow : Window, IEditor<TObject>, IResult<TResult>, new() {

        var dialog = new TWindow {
            ObjectToEdit = obj,
            Owner = service.GetRequiredService<MainWindow>(),
            WindowStartupLocation = WindowStartupLocation.CenterOwner,
        };

        dialog.DataContext = dialog;
        dialog.ShowDialog();

        return dialog.Result;
    }

}